package cn.iocoder.yudao.module.dr.service.sourcetag;

import cn.iocoder.yudao.module.dr.controller.admin.sourcetag.vo.SourceTagPageReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.sourcetag.vo.SourceTagSaveReqVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.source.SourceDO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.dr.controller.admin.sourcetag.vo.*;
import cn.iocoder.yudao.module.dr.dal.dataobject.sourcetag.SourceTagDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.dr.dal.mysql.sourcetag.SourceTagMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dr.enums.ErrorCodeConstants.*;

/**
 * 标签管理 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SourceTagServiceImpl implements SourceTagService {

    @Resource
    private SourceTagMapper sourceTagMapper;

    @Override
    public Long createSourceTag(SourceTagSaveReqVO createReqVO) {
        // 插入
        SourceTagDO sourceTag = BeanUtils.toBean(createReqVO, SourceTagDO.class);
        sourceTagMapper.insert(sourceTag);
        // 返回
        return sourceTag.getId();
    }

    @Override
    public void updateSourceTag(SourceTagSaveReqVO updateReqVO) {
        // 校验存在
        validateSourceTagExists(updateReqVO.getId());
        // 更新
        SourceTagDO updateObj = BeanUtils.toBean(updateReqVO, SourceTagDO.class);
        sourceTagMapper.updateById(updateObj);
    }

    @Override
    public void deleteSourceTag(Long id) {
        // 校验存在
        validateSourceTagExists(id);
        // 删除
        sourceTagMapper.deleteById(id);
    }

    private void validateSourceTagExists(Long id) {
        if (sourceTagMapper.selectById(id) == null) {
            throw exception(SOURCE_TAG_NOT_EXISTS);
        }
    }

    @Override
    public SourceTagDO getSourceTag(Long id) {
        return sourceTagMapper.selectById(id);
    }

    @Override
    public PageResult<SourceTagDO> getSourceTagPage(Long userId, SourceTagPageReqVO pageReqVO) {
        return sourceTagMapper.selectPage(userId,pageReqVO);
    }

    @Override
    public List<SourceDO> selectRef(Long tagId) {
        return sourceTagMapper.selectRef(tagId);
    }

}